import { defineComponent, onMounted, reactive, ref, toRefs } from 'vue'
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  RadioButton,
  RadioGroup,
  Row,
  Select,
  Textarea,
  Tree,
  TreeSelect
} from 'ant-design-vue'
import { ArrowDownOutlined, DeleteOutlined, SaveOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { useForm } from './use-form'
import { useDetail } from './use-detail'
import SvgIcon from '@/components/SvgIcon'

const Menu = defineComponent({
  name: 'Menu',
  setup() {
    const menuData = reactive({
      allMenuList: [],
      catalogAndMenuList: []
    })
    const searchText = ref<string>('')
    const operationStatus = ref<string>('add')
    const checkedKeys = ref<string[]>([])
    const { meta, state, setDetail, initForm, resetForm, getFormValues } = useForm()

    const { status, createOrUpdate, getMenuAllList, getCatalogAndMenuList, getMenuById, deleteMenuById } =
      useDetail(getFormValues)

    const onSearch = () => {}

    const onCancel = () => {
      resetForm()
      operationStatus.value = 'add'
    }

    const addMenu = () => {
      initForm()
      checkedKeys.value = []
      operationStatus.value = 'add'
    }

    const handleCommit = async () => {
      await createOrUpdate()
      onCancel()
      await fetchData()
    }

    const selectMenuEvent = async (selectedKeys: any) => {
      if (selectedKeys && selectedKeys.length > 0) {
        const menuId = selectedKeys[0]
        const menuData = await getMenuById(menuId)
        operationStatus.value = 'edit'
        setDetail(menuData)
      } else {
        addMenu()
      }
    }

    const deleteMenu = async () => {
      state.detailForm.code && (await deleteMenuById(state.detailForm.code))
      message.info('菜单删除成功')
      onCancel()
    }

    const addSubMenu = () => {
      const menuId = state.detailForm.code
      addMenu()
      if (menuId != null) {
        state.detailForm.parentCode = menuId
      }
    }
    const fetchData = async () => {
      menuData.allMenuList = await getMenuAllList()
      menuData.catalogAndMenuList = await getCatalogAndMenuList()
    }
    onMounted(async () => {
      initForm()
      await fetchData()
    })

    return {
      ...toRefs(state),
      ...toRefs(meta),
      ...toRefs(status),
      menuData,
      searchText,
      checkedKeys,
      operationStatus,
      onSearch,
      handleCommit,
      addMenu,
      selectMenuEvent,
      deleteMenu,
      addSubMenu
    }
  },

  render() {
    const {
      loading,
      detailForm,
      detailFormRef,
      menuData,
      rules,
      menuIconList,
      searchText,
      checkedKeys,
      operationStatus,
      menuTypeSelectValue,
      onSearch,
      handleCommit,
      addMenu,
      selectMenuEvent,
      deleteMenu,
      addSubMenu
    } = this
    return (
      <Row gutter={12} style={{ height: `calc(100vh - 120px)` }}>
        <Col span={6} style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
          <Button type='dashed' style={{ width: '100%', marginBottom: '10px' }} onClick={addMenu}>
            {'+ 新增 '}
          </Button>
          <Input
            v-model={[searchText, 'value']}
            placeholder='Search'
            search={onSearch}
            style={{ marginBottom: '10px' }}
            suffix={<SearchOutlined />}
          ></Input>
          <Card style={{ flex: '1', overflow: 'auto' }}>
            <Tree
              v-model:checkedKeys={checkedKeys}
              fieldNames={{ children: 'children', title: 'label', key: 'value' }}
              treeData={menuData.allMenuList}
              onSelect={selectMenuEvent}
            />
          </Card>
        </Col>
        <Col span={18} style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
          {operationStatus === 'add' && (
            <div>
              <Button
                style={{ marginBottom: '10px' }}
                icon={<SaveOutlined />}
                onClick={handleCommit}
                v-auth={['sys:menu:add']}
              >
                {'保存'}
              </Button>
            </div>
          )}
          {operationStatus === 'edit' && (
            <div>
              <Button
                style={{ marginBottom: '10px' }}
                icon={<SaveOutlined />}
                onClick={handleCommit}
                v-auth={['sys:menu:edit']}
              >
                {'更新'}
              </Button>
              <Button
                danger
                style={{ marginBottom: '10px', marginLeft: '10px' }}
                icon={<DeleteOutlined />}
                onClick={deleteMenu}
                v-auth={['sys:menu:delete']}
              >
                {'删除'}
              </Button>
              <Button
                type='dashed'
                style={{ marginBottom: '10px', marginLeft: '10px' }}
                icon={<ArrowDownOutlined />}
                onClick={addSubMenu}
              >
                {'增加下级'}
              </Button>
            </div>
          )}
          <Card title='基本信息' style={{ flex: '1', overflow: 'auto' }}>
            <Form
              ref={detailFormRef}
              model={detailForm}
              rules={rules}
              style={{ width: '100%', margin: '0 auto' }}
              onFinish={handleCommit}
              layout={'vertical'}
              loading={loading}
            >
              <Row gutter={16}>
                <Col span={8}>
                  <FormItem label={'菜单名称'} name={'name'}>
                    <Input v-model={[detailForm.name, 'value']} maxlength={20} placeholder='请输入内容' />
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label={'菜单类型'} name={'type'}>
                    <Select v-model={[detailForm.type, 'value']} options={menuTypeSelectValue} />
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label={'父级菜单'} name={'parentId'}>
                    <TreeSelect
                      allowClear={true}
                      v-model={[detailForm.parentCode, 'value']}
                      style={{ width: '100%' }}
                      fieldNames={{ children: 'children', title: 'label', key: 'value' }}
                      treeData={menuData.catalogAndMenuList}
                      dropdownStyle={{ maxHeight: '400px', overflow: 'auto' }}
                      placeholder='Please select'
                    />
                  </FormItem>
                </Col>
              </Row>

              {detailForm.type === 1 && (
                <>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem
                        label={'路由名称'}
                        name={'routeName'}
                        tooltip={'如果需要开启缓存，需保证页面 defineOptions 中的 name 与此处一致，建议使用驼峰。'}
                      >
                        <Input v-model={[detailForm.routeName, 'value']} maxlength={50} placeholder='请输入内容' />
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'组件名称'} name={'component'} tooltip={'tsx页面完整路径'}>
                        <Input v-model={[detailForm.component, 'value']} maxlength={50} placeholder='请输入内容' />
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem
                        label={'路由路径'}
                        name={'routePath'}
                        tooltip={
                          '定义应用中不同页面对应的 URL 路径，目录需以 / 开头，菜单项不用。例如：系统管理目录 /system，系统管理下的用户管理菜单 user。'
                        }
                      >
                        <Input v-model={[detailForm.routePath, 'value']} maxlength={20} placeholder='请输入内容' />
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={8}>
                      <FormItem label={'标签视图'} name={'affix'}>
                        <RadioGroup v-model={[detailForm.affix, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>隐藏</RadioButton>
                          <RadioButton value={1}>显示</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'是否隐藏'} name={'hideMenu'} tooltip={'是否隐藏菜单，是-隐藏，否-不隐藏'}>
                        <RadioGroup v-model={[detailForm.hideMenu, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>否</RadioButton>
                          <RadioButton value={1}>是</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'关闭缓存'} name={'alwaysShow'} tooltip={'【目录】只有一个子路由是否始终显示'}>
                        <RadioGroup v-model={[detailForm.ignoreKeepAlive, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>否</RadioButton>
                          <RadioButton value={1}>是</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                  </Row>

                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label={'图标'} name={'icon'}>
                        <Select v-model={[detailForm.icon, 'value']} options={menuIconList} allowClear={true}>
                          {{
                            option: ({ value, label }) => (
                              <div style={{ display: 'flex', alignItems: 'center' }}>
                                <SvgIcon name={value} size={18} />
                                <span style={{ marginLeft: '8px' }}>{label}</span>
                              </div>
                            )
                          }}
                        </Select>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem label={'排序'} name={'orderNo'} tooltip={'数字越小排名越靠前'}>
                        <InputNumber
                          v-model={[detailForm.orderNo, 'value']}
                          placeholder='请输入内容'
                          style={{ width: '100%' }}
                        />
                      </FormItem>
                    </Col>
                  </Row>
                  <FormItem label={'路由参数'} name={'params'} tooltip={'路由参数,格式为key=value&key=value&...'}>
                    <Textarea rows={3} v-model={[detailForm.params, 'value']} placeholder='请输入内容' />
                  </FormItem>
                </>
              )}

              {detailForm.type === 2 && (
                <>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem
                        label={'路由路径'}
                        name={'routePath'}
                        tooltip={
                          '定义应用中不同页面对应的 URL 路径，目录需以 / 开头，菜单项不用。例如：系统管理目录 /system，系统管理下的用户管理菜单 user。'
                        }
                      >
                        <Input v-model={[detailForm.routePath, 'value']} maxlength={20} placeholder='请输入内容' />
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'标签视图'} name={'affix'}>
                        <RadioGroup v-model={[detailForm.affix, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>隐藏</RadioButton>
                          <RadioButton value={1}>显示</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'是否隐藏'} name={'hideChildrenInMenu'} tooltip={'是否隐藏目录下面的所有子菜单'}>
                        <RadioGroup v-model={[detailForm.hideChildrenInMenu, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>否</RadioButton>
                          <RadioButton value={1}>是</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                  </Row>

                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label={'图标'} name={'icon'}>
                        <Select v-model={[detailForm.icon, 'value']} options={menuIconList} allowClear={true}>
                          {{
                            option: ({ value, label }) => (
                              <div style={{ display: 'flex', alignItems: 'center' }}>
                                <SvgIcon name={value} size={18} />
                                <span style={{ marginLeft: '8px' }}>{label}</span>
                              </div>
                            )
                          }}
                        </Select>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem label={'排序'} name={'orderNo'} tooltip={'数字越小排名越靠前'}>
                        <InputNumber
                          v-model={[detailForm.orderNo, 'value']}
                          placeholder='请输入内容'
                          style={{ width: '100%' }}
                        />
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'跳转路由'} name={'redirect'}>
                        <Input v-model={[detailForm.redirect, 'value']} maxlength={20} placeholder='请输入内容' />
                      </FormItem>
                    </Col>
                  </Row>
                </>
              )}

              {detailForm.type === 3 && (
                <>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label={'外链地址'} name={'externalSrc'}>
                        <Input v-model={[detailForm.externalSrc, 'value']} maxlength={100} placeholder='请输入内容' />
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'图标'} name={'icon'}>
                        <Select v-model={[detailForm.icon, 'value']} options={menuIconList} allowClear={true}>
                          {{
                            option: ({ value, label }) => (
                              <div style={{ display: 'flex', alignItems: 'center' }}>
                                <SvgIcon name={value} size={18} />
                                <span style={{ marginLeft: '8px' }}>{label}</span>
                              </div>
                            )
                          }}
                        </Select>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem label={'排序'} name={'orderNo'} tooltip={'数字越小排名越靠前'}>
                        <InputNumber
                          v-model={[detailForm.orderNo, 'value']}
                          placeholder='请输入内容'
                          style={{ width: '100%' }}
                        />
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={8}>
                      <FormItem label={'标签视图'} name={'visible'}>
                        <RadioGroup v-model={[detailForm.affix, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>隐藏</RadioButton>
                          <RadioButton value={1}>显示</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'是否展示'} name={'hideMenu'} tooltip={'是否隐藏菜单，是-隐藏，否-不隐藏'}>
                        <RadioGroup v-model={[detailForm.hideMenu, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>否</RadioButton>
                          <RadioButton value={1}>是</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                  </Row>
                </>
              )}

              {detailForm.type === 4 && (
                <Row gutter={16}>
                  <Col span={8}>
                    <FormItem label={'权限码'} name={'perm'}>
                      <Input v-model={[detailForm.perm, 'value']} maxlength={50} placeholder='请输入内容' />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label={'排序'} name={'orderNo'} tooltip={'数字越小排名越靠前'}>
                      <InputNumber
                        v-model={[detailForm.orderNo, 'value']}
                        placeholder='请输入内容'
                        style={{ width: '100%' }}
                      />
                    </FormItem>
                  </Col>
                </Row>
              )}

              {detailForm.type === 5 && (
                <>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label={'iframe地址'} name={'name'}>
                        <Input v-model={[detailForm.name, 'value']} maxlength={20} placeholder='请输入内容' />
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'图标'} name={'icon'}>
                        <Select v-model={[detailForm.icon, 'value']} options={menuIconList} allowClear={true}>
                          {{
                            option: ({ value, label }) => (
                              <div style={{ display: 'flex', alignItems: 'center' }}>
                                <SvgIcon name={value} size={18} />
                                <span style={{ marginLeft: '8px' }}>{label}</span>
                              </div>
                            )
                          }}
                        </Select>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem label={'排序'} name={'orderNo'} tooltip={'数字越小排名越靠前'}>
                        <InputNumber
                          v-model={[detailForm.orderNo, 'value']}
                          placeholder='请输入内容'
                          style={{ width: '100%' }}
                        />
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={8}>
                      <FormItem label={'标签视图'} name={'visible'}>
                        <RadioGroup v-model={[detailForm.affix, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>隐藏</RadioButton>
                          <RadioButton value={1}>显示</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label={'是否展示'} name={'alwaysShow'} tooltip={'【目录】只有一个子路由是否始终显示'}>
                        <RadioGroup v-model={[detailForm.hideMenu, 'value']} button-style={'solid'}>
                          <RadioButton value={0}>否</RadioButton>
                          <RadioButton value={1}>是</RadioButton>
                        </RadioGroup>
                      </FormItem>
                    </Col>
                  </Row>
                </>
              )}

              {detailForm.type === 6 && (
                <Row gutter={16}>
                  <Col span={8}>
                    <FormItem label={'权限码'} name={'perm'}>
                      <Input v-model={[detailForm.perm, 'value']} maxlength={50} placeholder='请输入内容' />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label={'排序'} name={'orderNo'} tooltip={'数字越小排名越靠前'}>
                      <InputNumber
                        v-model={[detailForm.orderNo, 'value']}
                        placeholder='请输入内容'
                        style={{ width: '100%' }}
                      />
                    </FormItem>
                  </Col>
                </Row>
              )}
            </Form>
          </Card>
        </Col>
      </Row>
    )
  }
})
export default Menu
